﻿Imports System.Xml
Imports System.IO
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.Threading

Public Class frmScanner
    Dim lastinsert As Int64
    Dim arret As Boolean = False

#Region "Traduction"
    Private _PasdeChaine As String = "Pas de chaines!"
    Public Property Pasdechaine As String
        Get
            Return _PasdeChaine
        End Get
        Set(ByVal value As String)
            _PasdeChaine = value
        End Set
    End Property
    Private _ChaineTrouve As String = "Chaines trouvées !"
    Public Property ChaineTrouve As String
        Get
            Return _ChaineTrouve
        End Get
        Set(ByVal value As String)
            _ChaineTrouve = value
        End Set
    End Property
    Private _MessageScanTermine As String = "Le scan des chaines est terminé"
    Public Property MessageScanTermine As String
        Get
            Return _MessageScanTermine
        End Get
        Set(ByVal value As String)
            _MessageScanTermine = value
        End Set
    End Property
#End Region

    Class scanner
        Friend Property Frequence As String
        'Friend Property Bandwidth As String
        Friend Mode As String
        'Friend type As String
        Friend device As String
        Friend Retour As String
        Friend norme As String
        Public Sub AuBoulot()
            Dim prsScan As New Process
            prsScan.StartInfo.FileName = ScanPath & "DVPiper.exe"
            prsScan.StartInfo.Arguments = "-checktimeout 3000 -minclean 0.00001 " & Frequence & " -type " & norme & " -devicenum " & device & "-tuning" & Mode & " -command listprogramxml -command exit"
            prsScan.StartInfo.UseShellExecute = False
            prsScan.StartInfo.CreateNoWindow = True
            prsScan.StartInfo.RedirectStandardOutput = True
            prsScan.Start()
            Application.DoEvents()
            'txbLog.Text += prsScan.StandardOutput.ReadToEnd
            'Dim ParseExtension As Collection(Of ChannelParam) = ParseXmlProgram(prsScan.StandardOutput.ReadToEnd)
            Retour = prsScan.StandardOutput.ReadToEnd
            prsScan.WaitForExit()
            prsScan.Close()
            System.Windows.Forms.Application.DoEvents()

            Application.DoEvents()

        End Sub

    End Class

    Private Sub btscan2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btscan2.Click
        'arret = False
        'btArreter.Enabled = True
        'btScan.Enabled = False

        lastinsert = InsertPlaylist(cboPays.SelectedItem.ToString & " " & cboNorme.SelectedItem.ToString & " device " & cboCarte.SelectedIndex.ToString)

        Dim listCanaux As DataTable = RechercheCanauxParPaysEtParNorme(cboPays.SelectedItem.ToString, cboNorme.SelectedItem.ToString)
        pgbScan.Value = 0
        pgbScan.Maximum = listCanaux.Rows.Count
        Dim ordering As Integer = 1
        Application.DoEvents()
        For i As Integer = 0 To listCanaux.Rows.Count - 1
            txbLog.Text += "Scanning : " & listCanaux.Rows(i).Item(0).ToString & Environment.NewLine
            'Dim prsScan As New Process
            'prsScan.StartInfo.FileName = ScanPath & "DVPiper.exe"
            'prsScan.StartInfo.Arguments = "-checktimeout 3000 -minclean 0.00001 " & listCanaux.Rows(i).Item(1).ToString & " -type " & cboNorme.SelectedItem.ToString & " -devicenum " & cboCarte.SelectedIndex + 1 & "-tuning" & cboMode.SelectedIndex + 1 & " -command listprogramxml -command exit"
            'prsScan.StartInfo.UseShellExecute = False
            'prsScan.StartInfo.CreateNoWindow = True
            'prsScan.StartInfo.RedirectStandardOutput = True
            'prsScan.Start()
            'Application.DoEvents()
            ''txbLog.Text += prsScan.StandardOutput.ReadToEnd
            'Dim ParseExtension As Collection(Of ChannelParam) = ParseXmlProgram(prsScan.StandardOutput.ReadToEnd)
            'prsScan.WaitForExit()
            'prsScan.Close()
            'System.Windows.Forms.Application.DoEvents()

            Dim onescan As New scanner
            onescan.Frequence = listCanaux.Rows(i).Item(1).ToString
            onescan.norme = cboNorme.SelectedItem.ToString
            onescan.device = (cboCarte.SelectedIndex + 1).ToString
            onescan.Mode = (cboMode.SelectedIndex + 1).ToString
            Dim ThreadScan As New Thread(AddressOf onescan.AuBoulot)
            ThreadScan.Start()
            ThreadScan.Join()
            Dim ParseExtension As Collection(Of ChannelParam) = ParseXmlProgram(onescan.Retour)




            Application.DoEvents()
            If ParseExtension.Count > 0 Then
                txbLog.Text += "    " & _ChaineTrouve & Environment.NewLine
                For Each channel As ChannelParam In ParseExtension
                    txbLog.Text += "        " & channel.Nomchaine & Environment.NewLine
                    Dim location As String = cboNorme.SelectedItem.ToString.ToLower & "://"
                    Dim dvbadaptater As String = ""
                    Dim extension As String = ""
                    Select Case cboNorme.SelectedItem.ToString
                        Case "DVB-T"
                            dvbadaptater = "dvb-adaptater=" & cboCarte.SelectedIndex.ToString
                            extension = listCanaux.Rows(i).Item(1).ToString.Replace("-frequency ", ":dvb-frequency=").Replace(" -bandwidth ", "000:dvb-bandwidth=") & ":program=" & channel.Program
                        Case "ATSC"
                            dvbadaptater = "atsc-adaptater=" & cboCarte.SelectedIndex.ToString
                            extension = listCanaux.Rows(i).Item(1).ToString.Replace("-frequency ", "dvb-frequency=").Replace(" -bandwidth ", ":dvb-bandwidth=") & ":program=" & channel.Program
                        Case "DVB-C"
                            dvbadaptater = "dvb-adaptater=" & cboCarte.SelectedIndex.ToString
                        Case "DVB-S"
                            dvbadaptater = "dvb-adaptater=" & cboCarte.SelectedIndex.ToString
                        Case "DVB-S2"
                            dvbadaptater = "dvb-adaptater=" & cboCarte.SelectedIndex.ToString

                    End Select

                    InsertChannel(lastinsert, location, channel.Nomchaine, dvbadaptater & extension, ordering)
                    ordering = ordering + 1
                Next
            Else
                txbLog.Text += "    " & _PasdeChaine & Environment.NewLine
            End If
            pgbScan.Value += 1
            Application.DoEvents()
            If arret Then
                Exit For
            End If
        Next
        btArreter.Enabled = False
        btScan.Enabled = True
        If ordering = 1 Then
            supprimerplaylist()
        End If

    End Sub

    Private Sub frmScanner_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Dim prsUnintall As New Process
        prsUnintall.StartInfo.FileName = "regsvr32"
        prsUnintall.StartInfo.Arguments = "/u /s " & """" & ScanPath & "Streamer.dll"""
        prsUnintall.StartInfo.UseShellExecute = False
        prsUnintall.StartInfo.CreateNoWindow = True
        prsUnintall.Start()
        prsUnintall.WaitForExit()
        prsUnintall.Close()
        'InitVlcPlayer(Mainform.pnlVideo.Handle)
    End Sub

    Private Sub frmScanner_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'DisposeVlcPlayer()
        StopMedia()

        Dim prsIntall As New Process
        prsIntall.StartInfo.FileName = "regsvr32"
        prsIntall.StartInfo.Arguments = "/s " & """" & ScanPath & "Streamer.dll" & """"
        prsIntall.StartInfo.UseShellExecute = False
        prsIntall.StartInfo.CreateNoWindow = True
        prsIntall.Start()
        prsIntall.WaitForExit()
        prsIntall.Close()

        Dim prsListdevice As New Process
        prsListdevice.StartInfo.FileName = ScanPath & "DVPiper.exe"
        prsListdevice.StartInfo.Arguments = "-listdevicexml"
        prsListdevice.StartInfo.UseShellExecute = False
        prsListdevice.StartInfo.CreateNoWindow = True
        prsListdevice.StartInfo.RedirectStandardOutput = True
        prsListdevice.Start()
        Dim strdevice As String = prsListdevice.StandardOutput.ReadToEnd
        strdevice = strdevice.Substring(0, strdevice.Length - 1)
        Dim toto As String = strdevice.Trim.Substring(strdevice.LastIndexOf(Environment.NewLine))
        If Not (strdevice.Trim.Substring(strdevice.LastIndexOf(Environment.NewLine)).Equals("No device found")) Then
            gbxScan.Enabled = True
            lblWarning.Visible = False

            strdevice = strdevice.Substring(strdevice.IndexOf("<devices>"))
            'txbLog.Text += strdevice & Environment.NewLine
            Dim xmldevice As New XmlDocument
            xmldevice.LoadXml(strdevice)
            Dim xmlnodedevice As XmlNodeList
            xmlnodedevice = xmldevice.GetElementsByTagName("name")

            For Each titi As XmlNode In xmlnodedevice
                cboCarte.Items.Add(titi.InnerText)
            Next

            Dim listPays As DataTable = RecherchePays()
            For i As Integer = 0 To listPays.Rows.Count - 1
                cboPays.Items.Add(listPays.Rows(i).Item(0).ToString)
            Next
            cboPays.SelectedIndex = 0
            Dim listNorme As DataTable = RechercheNorme()
            For j As Integer = 0 To listNorme.Rows.Count - 1
                cboNorme.Items.Add(listNorme.Rows(j).Item(0).ToString)
            Next
            cboNorme.SelectedIndex = 0
            cboMode.SelectedIndex = 0
            cboCarte.SelectedIndex = 0
        Else
            gbxScan.Enabled = False
            lblWarning.Visible = True
        End If

        prsListdevice.WaitForExit()
        prsListdevice.Close()

    End Sub

    Private Sub btScan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btScan.Click
        arret = False
        btArreter.Enabled = True
        btScan.Enabled = False

        lastinsert = InsertPlaylist(cboPays.SelectedItem.ToString & " " & cboNorme.SelectedItem.ToString & " device " & cboCarte.SelectedIndex.ToString)

        Dim listCanaux As DataTable = RechercheCanauxParPaysEtParNorme(cboPays.SelectedItem.ToString, cboNorme.SelectedItem.ToString)
        pgbScan.Value = 0
        pgbScan.Maximum = listCanaux.Rows.Count
        Dim ordering As Integer = 1
        Application.DoEvents()
        For i As Integer = 0 To listCanaux.Rows.Count - 1
            txbLog.Text += "Scanning : " & listCanaux.Rows(i).Item(0).ToString & Environment.NewLine
            Dim prsScan As New Process
            prsScan.StartInfo.FileName = ScanPath & "DVPiper.exe"
            prsScan.StartInfo.Arguments = "-checktimeout 3000 -minclean 0.00001 " & listCanaux.Rows(i).Item(1).ToString & " -type " & cboNorme.SelectedItem.ToString & " -devicenum " & cboCarte.SelectedIndex + 1 & "-tuning" & cboMode.SelectedIndex + 1 & " -command listprogramxml -command exit"
            prsScan.StartInfo.UseShellExecute = False
            prsScan.StartInfo.CreateNoWindow = True
            prsScan.StartInfo.RedirectStandardOutput = True
            prsScan.Start()
            Application.DoEvents()
            'txbLog.Text += prsScan.StandardOutput.ReadToEnd
            Dim ParseExtension As Collection(Of ChannelParam) = ParseXmlProgram(prsScan.StandardOutput.ReadToEnd)
            prsScan.WaitForExit()
            prsScan.Close()
            System.Windows.Forms.Application.DoEvents()

            Application.DoEvents()
            If ParseExtension.Count > 0 Then
                txbLog.Text += "    " & _ChaineTrouve & Environment.NewLine
                For Each channel As ChannelParam In ParseExtension
                    txbLog.Text += "        " & channel.Nomchaine & Environment.NewLine
                    Dim location As String = cboNorme.SelectedItem.ToString.ToLower & "://"
                    Dim dvbadaptater As String = ""
                    Dim extension As String = ""
                    Select Case cboNorme.SelectedItem.ToString
                        Case "DVB-T"
                            dvbadaptater = "dvb-adaptater=" & cboCarte.SelectedIndex.ToString
                            extension = listCanaux.Rows(i).Item(1).ToString.Replace("-frequency ", ":dvb-frequency=").Replace(" -bandwidth ", "000:dvb-bandwidth=") & ":program=" & channel.Program
                        Case "ATSC"
                            dvbadaptater = "atsc-adaptater=" & cboCarte.SelectedIndex.ToString
                            extension = listCanaux.Rows(i).Item(1).ToString.Replace("-frequency ", "dvb-frequency=").Replace(" -bandwidth ", ":dvb-bandwidth=") & ":program=" & channel.Program
                        Case "DVB-C"
                            dvbadaptater = "dvb-adaptater=" & cboCarte.SelectedIndex.ToString
                        Case "DVB-S"
                            dvbadaptater = "dvb-adaptater=" & cboCarte.SelectedIndex.ToString
                        Case "DVB-S2"
                            dvbadaptater = "dvb-adaptater=" & cboCarte.SelectedIndex.ToString

                    End Select

                    InsertChannel(lastinsert, location, channel.Nomchaine, dvbadaptater & extension, ordering)
                    ordering = ordering + 1
                Next
            Else
                txbLog.Text += "    " & _PasdeChaine & Environment.NewLine
            End If
            pgbScan.Value += 1
            Application.DoEvents()
            If arret Then
                Exit For
            End If
        Next
        pgbScan.Value = 0
        btArreter.Enabled = False
        btScan.Enabled = True
        If ordering = 1 Then
            supprimerplaylist()
        End If
        MessageBox.Show(_MessageScanTermine, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
    End Sub
    Private Sub supprimerplaylist()
        DeletePlaylist(lastinsert)
    End Sub
    Private Function ParseXmlProgram(ByVal strXML As String) As Collection(Of ChannelParam)
        Dim retours As New Collection(Of ChannelParam)
        Dim retour As ChannelParam
        retour.Nomchaine = ""
        retour.Program = ""
        Dim test As Integer = strXML.IndexOf("<programs>")
        If test > 0 Then
            'Chouette, il y a des chaines sur cette frequence !
            Dim xmlprogram As New XmlDocument
            xmlprogram.LoadXml(strXML.Substring(test, strXML.IndexOf("</programs>") + 11 - test))
            Dim program As XmlNodeList = xmlprogram.ChildNodes(0).ChildNodes
            For Each nodeprogram As XmlNode In program
                Dim hasVideo As Boolean = False
                Dim hasAudio As Boolean = False

                'Dim hasAudio As Boolean = False
                Dim listpacket As XmlNodeList = nodeprogram.ChildNodes
                For Each toto As XmlNode In listpacket
                    If toto.Name = "packet" Then
                        If toto("type").InnerText.Length > 4 AndAlso toto("type").InnerText.Substring(0, 5) = "Video" Then
                            hasVideo = True
                            'Exit For
                        End If
                        If toto("type").InnerText.Length > 4 AndAlso toto("type").InnerText.Substring(0, 5) = "Audio" Then
                            hasAudio = True
                            'Exit For
                        End If

                    End If
                Next


                If hasVideo OrElse ckbRadio.Checked Then
                    If hasAudio Then
                        If nodeprogram("access").InnerText.Equals("FTA") OrElse (Not ckbFTA.Checked) Then
                            Try
                                'If nodeprogram("name").InnerText = "FRANCE BLEU IDF" Then
                                '    Dim bidon As String = "kj"
                                'End If
                                retour.Nomchaine = nodeprogram("name").InnerText
                                retour.Program = nodeprogram("id").InnerText
                                retours.Add(retour)
                            Catch ex As Exception

                            End Try

                        End If
                    End If

                End If
            Next
        End If
        Return retours
    End Function

    Friend Structure ChannelParam
        Public Nomchaine As String
        Public Program As String

    End Structure

    Private Sub btquitter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btquitter.Click
        Me.Close()
    End Sub

    Private Sub btArreter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btArreter.Click
        arret = True
    End Sub

End Class